package com.itwc.websocketdemo.service;

import com.itwc.websocketdemo.entity.SysUser;
import com.itwc.websocketdemo.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 用户服务类
 */
@Slf4j
@Service
public class UserService {
    
    private static final Logger log = LoggerFactory.getLogger(UserService.class);
    
    @Autowired
    private SysUserMapper sysUserMapper;
    
    @Autowired
    private WebSocketService webSocketService;
    
    /**
     * 用户登录
     */
    public SysUser login(String userName, String password) {
        SysUser user = sysUserMapper.selectUserByUserName(userName);
        
        if (user == null) {
            log.warn("用户不存在: {}", userName);
            return null;
        }
        
        if (!"0".equals(user.getStatus())) {
            log.warn("用户已停用: {}", userName);
            return null;
        }
        
        // 简单密码验证（实际项目中应该使用加密）
        if (!password.equals(user.getPassword())) {
            log.warn("密码错误: {}", userName);
            return null;
        }
        
        // 更新登录信息
        sysUserMapper.updateUserLoginInfo(user.getUserId(), "127.0.0.1", LocalDateTime.now());
        
        log.info("用户登录成功: {}", userName);
        return user;
    }
    
    /**
     * 用户上线处理
     */
    public void handleUserOnline(Long userId, String sessionId) {
        log.info("👤 ========== 用户上线处理开始 ==========");
        log.info("👤 用户ID: {}", userId);
        log.info("👤 会话ID: {}", sessionId);
        
        // 标记用户在线
        log.info("👤 正在将用户添加到在线用户列表...");
        webSocketService.userOnline(userId, sessionId);
        log.info("👤 ✅ 用户已添加到在线列表");
        
        // 获取当前在线用户数量
        int onlineCount = webSocketService.getOnlineUserIds().size();
        log.info("👤 当前在线用户总数: {}", onlineCount);
        log.info("👤 当前在线用户列表: {}", webSocketService.getOnlineUserIds());
        
        log.info("👤 ========== 用户上线处理完成 ==========");
    }
    
    /**
     * 用户下线处理
     */
    public void handleUserOffline(Long userId) {
        webSocketService.userOffline(userId);
        log.info("用户 {} 下线处理完成", userId);
    }
    
    /**
     * 根据ID获取用户
     */
    public SysUser getUserById(Long userId) {
        return sysUserMapper.selectUserById(userId);
    }
}